
from PySide6.QtCore import QFile
from PySide6.QtUiTools import QUiLoader

from src.main.server.controller.score_controller import ScoreController


class EditScoreWindow:

    def __init__(self, main_window, data=None):
        self.data = None
        if data:
            self.data = data
        self._load_ui()
        self.main_window = main_window

    def _load_ui(self):
        path = "../../../qt_ui/edit_score.ui"
        file = QFile(path)
        try:
            loader = QUiLoader()
            self.window = loader.load(file)
            self.window.pushButton_2.clicked.connect(self.close_window)

        finally:
            file.close()

        if self.window:
            self.window.show()  # 显示独立窗口
        else:
            print("加载 UI 失败，请检查文件路径或内容")

        if self.data:
            """有数据则回显数据"""
            self.get_info()

    def get_info(self):
        self.window.lineEdit.setText(self.data[0][0])           #申请人
        self.window.lineEdit_2.setText(self.data[0][1])         #项目名称

        # 设置 QSpinBox 的值
        score = int(self.data[0][2])
        self.window.spinBox.setValue(score)

        self.window.pushButton.clicked.connect(self.submit)

    def submit(self):

        vol_name = self.window.lineEdit.text()
        server_name = self.window.lineEdit_2.text()
        score = str(self.window.spinBox.value())

        ScoreController().update((score, vol_name, server_name))
        print("推送成功")
        self.main_window.new_data()
        self.close_window()

    def close_window(self):
        """关闭当前窗口"""
        self.window.close()

def edit_score_window(self, data = None):
    if data:
        self.edit_window = EditScoreWindow(self, data)
    else:
        self.edit_window = EditScoreWindow(self)